package com.pinyougou.sellergoods.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pinyougou.mapper.TbSpecificationOptionMapper;
import com.pinyougou.mapper.TbTypeTemplateMapper;
import com.pinyougou.pojo.TbSpecificationOption;
import com.pinyougou.pojo.TbSpecificationOptionExample;
import com.pinyougou.pojo.TbSpecificationOptionExample.Criteria;
import com.pinyougou.pojo.TbTypeTemplate;
import com.pinyougou.sellergoods.service.TypeTemplateService;
@Service(timeout=10000)
public class TbTypeTemplateServiceImpl implements TypeTemplateService{

	@Autowired
	private TbTypeTemplateMapper maper;
	@Override
	public List<TbTypeTemplate> findAll() {
		
		List<TbTypeTemplate> selectByExample = maper.selectByExample(null);
		
		return selectByExample;
		
	}
	@Override
	public TbTypeTemplate findOne(long id) {
		
		return maper.selectByPrimaryKey(id);
	}
	@Autowired
	private TbSpecificationOptionMapper specificationOption;
	
	//制作一个集合里面放入map,map里面是规格选项表
	
	@Override
	public List<Map> findSpecList(Long id) {
	
		TbTypeTemplate typeTemplate = maper.selectByPrimaryKey(id);
		
		//查出来的模板对象放入转成json字符串
		List<Map> list = JSON.parseArray(typeTemplate.getSpecIds(), Map.class);
		
		for(Map map:list) {
			
			
			TbSpecificationOptionExample example= new TbSpecificationOptionExample();
			Criteria criteria = example.createCriteria();
			criteria.andSpecIdEqualTo(new Long((Integer)map.get("id")));
			
			List<TbSpecificationOption> op = specificationOption.selectByExample(example);
			map.put("options", op);
			
		}
		
		
		return list;
	}
	@Autowired
	private RedisTemplate template;	
	/**
	 * 从模板中获取到brand和spec存到redis中
	 */
	public  void saveToRedis() {
		
		List<TbTypeTemplate> typeTemplate= findAll();
		
		for(TbTypeTemplate tt:typeTemplate) {
			
			List<Map> brandList = JSON.parseArray(tt.getBrandIds(),Map.class);
			
			template.boundHashOps("brandList").put(tt.getId(), brandList);
			System.out.println("模板存入数据到缓存");
			List<Map> specList = findSpecList(tt.getId());
			
			template.boundHashOps("specList").put(tt.getId(), specList);
			System.out.println("规格存入数据到缓存");
		}
		
		
		
	}
	
	
	

}
